from __future__ import annotations

from dataclasses import dataclass
from typing import Dict, Any, List
from datetime import datetime

from quantcore.db import Mongo


@dataclass
class BrokerAPI:
    """券商接口抽象。后续可替换为真实券商 API 集成。"""

    def place_order(self, order: Dict[str, Any]) -> Dict[str, Any]:
        order = dict(order)
        order["status"] = "FILLED"
        order["_id"] = order.get("_id") or str(datetime.utcnow().timestamp())
        return order


@dataclass
class Executor:
    broker: BrokerAPI

    def execute_orders(self, orders: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
        """执行委托：写入订单与成交集合（当前为模拟成交）。"""
        col_orders = Mongo.col("orders")
        col_trades = Mongo.col("trades")
        executed: List[Dict[str, Any]] = []
        for order in orders:
            res = self.broker.place_order(order)
            col_orders.insert_one(res)
            trade = {
                "_id": res["_id"],
                "order_id": res["_id"],
                "filled_time": datetime.utcnow(),
                "symbol": res["symbol"],
                "filled_price": res["price"],
                "filled_qty": res["qty"],
                "commission": 0.0,
                "tax": 0.0,
                "impact_cost": 0.0,
            }
            col_trades.insert_one(trade)
            executed.append(res)
        return executed




